from dynaconf import Dynaconf
from pathlib import Path
import keyring
from cryptography.fernet import Fernet
import os
import json
import csv
from typing import List, Dict, Optional

# 配置文件路径
CONFIG_PATH = Path.home() / ".bitget_tool"
CONFIG_PATH.mkdir(exist_ok=True)
CONFIG_FILE = CONFIG_PATH / "config.json"

# 初始化配置
settings = Dynaconf(
    envvar_prefix="BITGET",
    settings_files=[CONFIG_PATH / "settings.toml"],
    environments=True,
    load_dotenv=True,
)

class ConfigManager:
    def __init__(self):
        self._fernet = None
        self._load_or_create_key()
        
    def _load_or_create_key(self):
        """加载或创建加密密钥"""
        key = keyring.get_password("bitget_tool", "encryption_key")
        if not key:
            key = Fernet.generate_key().decode()
            keyring.set_password("bitget_tool", "encryption_key", key)
        self._fernet = Fernet(key.encode())
        
    def encrypt(self, data: str) -> str:
        """加密数据"""
        return self._fernet.encrypt(data.encode()).decode()
        
    def decrypt(self, encrypted_data: str) -> str:
        """解密数据"""
        return self._fernet.decrypt(encrypted_data.encode()).decode()
        
    def save_api_key(self, api_key: str, api_secret: str, passphrase: str):
        """保存API密钥"""
        config = {
            "api_key": self.encrypt(api_key),
            "api_secret": self.encrypt(api_secret),
            "passphrase": self.encrypt(passphrase)
        }
        with open(CONFIG_FILE, 'w') as f:
            json.dump(config, f, indent=4)
        
    def get_api_key(self) -> tuple:
        """获取API密钥"""
        try:
            if not CONFIG_FILE.exists():
                return None, None, None
                
            with open(CONFIG_FILE, 'r') as f:
                config = json.load(f)
                return (
                    self.decrypt(config.get('api_key', '')),
                    self.decrypt(config.get('api_secret', '')),
                    self.decrypt(config.get('passphrase', ''))
                )
        except Exception as e:
            print(f"获取API密钥失败: {str(e)}")
            return None, None, None
            
    def load_api_config(self, config_file: str) -> Optional[tuple]:
        """从配置文件加载API密钥"""
        try:
            with open(config_file, 'r') as f:
                config = json.load(f)
                return (
                    config.get('api_key'),
                    config.get('api_secret'),
                    config.get('passphrase')
                )
        except Exception as e:
            print(f"加载配置文件失败: {str(e)}")
            return None
            
    def save_api_config(self, config_file: str, api_key: str, api_secret: str, passphrase: str):
        """保存API配置到文件"""
        try:
            with open(config_file, 'w') as f:
                json.dump({
                    'api_key': api_key,
                    'api_secret': api_secret,
                    'passphrase': passphrase
                }, f, indent=4)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {str(e)}")
            return False
            
    @staticmethod
    def load_withdraw_addresses(csv_file: str) -> List[Dict]:
        """从CSV文件加载提币地址"""
        addresses = []
        try:
            with open(csv_file, 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
                for row in reader:
                    addresses.append({
                        'address': row.get('address', ''),
                        'chain': row.get('chain', ''),
                        'amount': float(row.get('amount', 0)),
                        'coin': row.get('coin', '')
                    })
            return addresses
        except Exception as e:
            print(f"加载提币地址失败: {str(e)}")
            return []
            
    @staticmethod
    def save_withdraw_addresses(csv_file: str, addresses: List[Dict]):
        """保存提币地址到CSV文件"""
        try:
            with open(csv_file, 'w', encoding='utf-8', newline='') as f:
                writer = csv.DictWriter(f, fieldnames=['address', 'chain', 'amount', 'coin'])
                writer.writeheader()
                writer.writerows(addresses)
            return True
        except Exception as e:
            print(f"保存提币地址失败: {str(e)}")
            return False 